<template>
    <div class="weather" v-if="reload">
        <el-card class="box-card" shadow="hover">
            <template #header>
                <div class="card-header">
                    <span>实时天气</span>
                </div>
            </template>

            <el-descriptions
                class="margin-top"
                :title="city"
                :column="2"
                :size="size"
                border
                v-if="nowInfo.now"
            >
                <template #title>
                    <span v-if="showEdit">
                        <el-autocomplete
                            v-model="querySearchCity"
                            :trigger-on-focus="false"
                            :fetch-suggestions="querySearchAsync"
                            placeholder="Please input"
                            @select="handleSelect"
                            v-on:blur="showEdit = false"
                        >
                        </el-autocomplete>
                        <el-button type="primary" @click="showEdit = false">确认</el-button
                        >
                    </span>

                    <span v-else>
                        {{ city }}
                        <el-icon class="refresh-icon" @click="showEdit = true"
                            ><Edit
                        /></el-icon>
                    </span>
                </template>

                <template #extra>
                    <el-icon class="refresh-icon" @click="handleRefreshClick"
                        ><Refresh
                    /></el-icon>
                </template>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <Sunny />
                            </el-icon>
                            天气
                        </div>
                    </template>
                    {{ nowInfo.now.text }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <HotWater />
                            </el-icon>
                            温度
                        </div>
                    </template>
                    {{ nowInfo.now.temp }}℃
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <WindPower />
                            </el-icon>
                            风向
                        </div>
                    </template>
                    {{ nowInfo.now.windDir }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <Odometer />
                            </el-icon>
                            风速
                        </div>
                    </template>
                    {{ nowInfo.now.windSpeed }}级
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <PieChart />
                            </el-icon>
                            湿度
                        </div>
                    </template>
                    {{ nowInfo.now.humidity }}%
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <RefreshLeft />
                            </el-icon>
                            更新时间
                        </div>
                    </template>
                    {{ nowInfo.now.obsTime.slice(0, 16).replace("T", " ") }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <Link />
                            </el-icon>
                            数据来源
                        </div>
                    </template>
                    <el-link href="https://www.qweather.com/" target="_blank">和风天气</el-link>
                </el-descriptions-item>
            </el-descriptions>
        </el-card>

        <el-card class="box-card" shadow="hover">
            <vue-echarts :option="hourInfo" style="height: 400px" />
        </el-card>

        <el-card class="box-card" shadow="hover">
            <template #header>
                <div class="card-header">
                    <span>未来7天天气</span>
                </div>
            </template>

            <vue-echarts :option="dayInfo" style="height: 400px" />

            <el-table :data="weatherInfo.daily" style="width: 100%">
                <el-table-column label="日期" width="180">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <el-icon><timer /></el-icon>
                            <span style="margin-left: 10px">{{
                                scope.row.fxDate
                            }}</span>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="最低温" width="80">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.tempMin }}℃</span>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="最高温" width="80">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.tempMax }}℃</span>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="textDay" label="白天天气" width="100" />
                <el-table-column
                    prop="textNight"
                    label="夜晚天气"
                    width="100"
                />
                <el-table-column prop="windDirDay" label="风向" width="180" />
                <el-table-column prop="sunrise" label="日出" width="180" />
                <el-table-column prop="sunset" label="日落" width="180" />

                <el-table-column label="湿度" width="80">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span>{{ scope.row.humidity }}%</span>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column prop="uvIndex" label="紫外线强度" />
            </el-table>
        </el-card>
    </div>
</template>

<script>
import {
    reactive,
    toRefs,
    onBeforeMount,
    onUnmounted,
    watch,
    nextTick,
} from "vue";
import request from "@/utils/request.js";
import { VueEcharts } from "vue3-echarts";

export default {
    name: "SysInfo",
    components: { VueEcharts },

    setup() {
        const state = reactive({
            reload: true,
            weatherInfo: {},
            nowInfo: {},
            hourInfo: {},
            dayInfo: {},
            key: "115ee120508d447b8ea68a27d4c78472",
            location: 101021200,
            city: "徐汇区",
            querySearchCity: "徐汇区",
            showEdit: false,
        });

        const hourInfoTemplate = {
            title: {
                text: "24小时天气预报",
            },
            tooltip: {
                trigger: "axis",
            },
            legend: {},
            toolbox: {
                show: false,
                feature: {
                    dataZoom: {
                        yAxisIndex: "none",
                    },
                    magicType: { type: ["line", "bar"] },
                    restore: {},
                    saveAsImage: {},
                },
            },
            xAxis: [
                {
                    type: "category",
                    boundaryGap: false,
                    data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
                },
                {
                    data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
                    axisLine: {
                        //轴线不显示
                        show: false,
                    },
                    position: "bottom", //x轴线位置
                    offset: -30, //轴线偏移量，当position:'bottom'，正值向下移，负值向上移
                },
            ],
            yAxis: {
                type: "value",
                axisLabel: {
                    formatter: "{value} °C",
                },
            },
            series: [
                {
                    name: "温度",
                    type: "line",
                    data: [10, 11, 13, 11, 12, 12, 9],
                    markPoint: {
                        data: [
                            { type: "max", name: "Max" },
                            { type: "min", name: "Min" },
                        ],
                    },
                    markLine: {
                        data: [{ type: "average", name: "Avg" }],
                    },
                    label: {
                        show: true,
                        position: "bottom",
                        formatter: "{c} °C",
                    },
                },
            ],
        };

        let dayInfoTemplate = {
            title: {
                text: "",
            },
            tooltip: {
                trigger: "axis",
            },
            legend: {},
            toolbox: {
                show: false,
                feature: {
                    dataZoom: {
                        yAxisIndex: "none",
                    },
                    dataView: { readOnly: false },
                    magicType: { type: ["line", "bar"] },
                    restore: {},
                    saveAsImage: {},
                },
            },
            xAxis: {
                type: "category",
                boundaryGap: false,
                data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
            },
            yAxis: {
                type: "value",
                axisLabel: {
                    formatter: "{value} °C",
                },
            },
            series: [
                {
                    name: "最高温",
                    type: "line",
                    data: [10, 11, 13, 11, 12, 12, 9],
                    markPoint: {
                        data: [
                            { type: "max", name: "Max" },
                            { type: "min", name: "Min" },
                        ],
                    },
                    markLine: {
                        data: [{ type: "average", name: "Avg" }],
                    },
                    label: {
                        show: true,
                        position: "bottom",
                        formatter: "{c} °C",
                    },
                },
                {
                    name: "最低温",
                    type: "line",
                    data: [1, -2, 2, 5, 3, 2, 0],
                    markPoint: {
                        data: [
                            {
                                name: "周最低",
                                value: -2,
                                xAxis: 1,
                                yAxis: -1.5,
                            },
                        ],
                    },
                    markLine: {
                        data: [
                            { type: "average", name: "Avg" },
                            [
                                {
                                    symbol: "none",
                                    x: "90%",
                                    yAxis: "max",
                                },
                                {
                                    symbol: "circle",
                                    label: {
                                        position: "start",
                                        formatter: "Max",
                                    },
                                    type: "max",
                                    name: "最高点",
                                },
                            ],
                        ],
                    },
                    label: {
                        show: true,
                        position: "bottom",
                        formatter: "{c} °C",
                    },
                },
            ],
        };

        let timer = null;

        onBeforeMount(() => {
            state.city = localStorage.getItem("city")
                ? localStorage.getItem("city")
                : state.city;
            state.location = localStorage.getItem("location")
                ? localStorage.getItem("location")
                : state.location;
            state.querySearchCity = state.city;
            handleRefreshClick();

            timer = setInterval(() => {
                handleRefreshClick();
            }, 1000 * 60 * 30);
        });

        onUnmounted(() => {
            if (timer) {
                clearInterval(timer); //清除定时器
                timer = null;
            }
        });

        watch(
            () => state.location,
            () => {
                handleRefreshClick();
            }
        );

        function reload() {
            state.reload = false;
            nextTick(() => {
                state.reload = true;
            });
        }

        async function updateNow() {
            try {
                let url = `https://devapi.qweather.com/v7/weather/now?key=${state.key}&location=${state.location}`;
                let res = await request.get(url);
                console.log("res:", res);
                state.nowInfo = res;
            } catch (error) {
                console.error(error);
            }
        }

        async function update24() {
            try {
                let url = `https://devapi.qweather.com/v7/weather/24h?key=${state.key}&location=${state.location}`;
                let res = await request.get(url);
                console.log("res:", res);
                let hourly = res.hourly;
                let hourInfo = hourInfoTemplate;
                hourInfo.xAxis[0].data = [];
                hourInfo.series[0].data = [];
                for (let i = 0; i < hourly.length; i++) {
                    let hour = hourly[i];
                    console.log(hour);
                    hourInfo.xAxis[0].data[i] = hour.fxTime.slice(11, 16);
                    hourInfo.series[0].data[i] = hour.temp;
                }

                state.hourInfo = hourInfo;
                console.log(state.hourInfo);

                reload();
            } catch (error) {
                console.error(error);
            }
        }

        async function update7d() {
            try {
                let url = `https://devapi.qweather.com/v7/weather/7d?key=${state.key}&location=${state.location}`;
                let res = await request.get(url);
                console.log("res:", res);
                state.weatherInfo = res;

                let daily = res.daily;
                let dailyInfo = dayInfoTemplate;
                dailyInfo.xAxis.data = [];
                dailyInfo.series[0].data = [];
                for (let i = 0; i < daily.length; i++) {
                    let hour = daily[i];
                    console.log(hour);
                    dailyInfo.xAxis.data[i] = hour.fxDate;
                    dailyInfo.series[0].data[i] = hour.tempMax;
                    dailyInfo.series[1].data[i] = hour.tempMin;
                }

                state.dayInfo = dailyInfo;
                console.log(state.dayInfo);

                reload();
            } catch (error) {
                console.error(error);
            }
        }

        function handleRefreshClick() {
            update7d();
            update24();
            updateNow();

            reload();
        }

        async function querySearchAsync(queryString, cb) {
            let cityArr = [];

            try {
                let url = `https://geoapi.qweather.com/v2/city/lookup?key=${state.key}&location=${queryString}`;
                let res = await request.get(url);
                cityArr = res.location.map((item) => {
                    return { value: item.name, ...item };
                });
            } catch (error) {
                console.error(error);
            }

            cb(cityArr);
            console.log(cityArr);
        }

        function handleSelect(item) {
            console.log(item);
            state.city = item.name;
            state.location = item.id;

            localStorage.setItem("city", item.name);
            localStorage.setItem("location", item.id);

            state.showEdit = false;
        }

        return {
            ...toRefs(state),
            handleRefreshClick,
            querySearchAsync,
            handleSelect,
        };
    },
};
</script>

<style scoped>
.box-card {
    margin: 20px 20px;
}

.refresh-icon {
    cursor: pointer;
}

.refresh-icon:hover {
    color: blue;
}
</style>

